class Solution {
public:
    string reverseWords(string s) {
        reverse(s.begin(), s.end());
        int n = s.size(), index = 0;
        for(int i = 0; i < n; ++i)
        {
            if(s[i] != ' ')
            {
                if(index != 0) s[index++] = ' ';
                int end = i;
                while(end < n && s[end] != ' ') s[index++] = s[end++];

                reverse(s.begin() + index - (end - i), s.begin() + index);
                i = end;
            }
        }
        s.erase(s.begin() + index, s.end());
        return s; 
    }
};
